import { create } from 'zustand'

// 轻量内置类型定义与内存版 API，避免未引入真实 API 时的运行时错误
export type NotificationCategory = 'risk' | 'ops' | 'logistics' | 'marketing'

export interface NotificationRecord {
  id: string
  title: string
  message: string
  category: NotificationCategory
  createdAt: string
  read: boolean
}

export type NotificationItem = NotificationRecord

// 内存数据与简易 API（如后端/真实 API 接入，可用真实 API 覆盖这些实现）
const __memoryNotifications: NotificationItem[] = []

const notificationAPI = {
  list: async () => {
    const items = [...__memoryNotifications].slice(0, 20)
    const unreadCount = items.filter((i) => !i.read).length
    const lastSyncedAt = new Date().toISOString()
    return Promise.resolve({ data: { items, unreadCount, lastSyncedAt } })
  },
  markAllRead: async () => {
    __memoryNotifications.forEach((n) => (n.read = true))
    return Promise.resolve({ data: { success: true } })
  },
  markRead: async (id: string, isRead = true) => {
    const it = __memoryNotifications.find((n) => n.id === id)
    if (it) it.read = !!isRead
    return Promise.resolve({ data: { success: true } })
  },
}

interface NotificationState {
  items: NotificationItem[]
  loading: boolean
  lastSyncedAt?: string
  unreadCount: number
  fetchLatest: () => Promise<void>
  markAllRead: () => Promise<void>
  markAsRead: (id: string) => Promise<void>
  pushNotification: (payload: Omit<NotificationItem, 'id' | 'createdAt' | 'read'> & { createdAt?: string }) => void
}

const createId = () => {
  if (typeof crypto !== 'undefined' && crypto.randomUUID) {
    return crypto.randomUUID()
  }
  return Math.random().toString(36).slice(2)
}

export const useNotificationStore = create<NotificationState>((set, get) => ({
  items: [],
  loading: false,
  unreadCount: 0,
  fetchLatest: async () => {
    if (get().loading) return
    set({ loading: true })
    try {
      const response = await notificationAPI.list()
      const { items, unreadCount, lastSyncedAt } = response.data
      set({
        items,
        unreadCount,
        lastSyncedAt: lastSyncedAt || new Date().toISOString(),
        loading: false,
      })
    } catch (error) {
      console.error('fetchLatest notifications failed', error)
      set({ loading: false })
    }
  },
  markAllRead: async () => {
    try {
      await notificationAPI.markAllRead()
    } catch (error) {
      console.error('markAllRead notifications failed', error)
    }
    set({
      items: get().items.map((item) => ({ ...item, read: true })),
      unreadCount: 0,
      lastSyncedAt: new Date().toISOString(),
    })
  },
  markAsRead: async (id: string) => {
    set((state) => ({
      items: state.items.map((item) => (item.id === id ? { ...item, read: true } : item)),
      unreadCount: Math.max(0, state.unreadCount - (state.items.find((item) => item.id === id && !item.read) ? 1 : 0)),
    }))
    try {
      await notificationAPI.markRead(id, true)
      const response = await notificationAPI.list()
      set((state) => ({
        unreadCount: response.data.unreadCount ?? state.unreadCount,
        lastSyncedAt: response.data.lastSyncedAt || new Date().toISOString(),
        items: response.data.items,
      }))
    } catch (error) {
      console.error('markAsRead notification failed', error)
    }
  },
  pushNotification: (payload) => {
    const createdAt = payload.createdAt || new Date().toISOString()
    const item: NotificationItem = {
      id: createId(),
      read: false,
      createdAt,
      ...payload,
    }
    const items = [item, ...get().items].slice(0, 20)
    set({
      items,
      unreadCount: items.filter((it) => !it.read).length,
    })
  },
}))

